const qiniu = require('qiniu');
const Minio = require('minio');
const fs = require('fs');
const { MINIOCONFIG, QINIUCONFIG } = require('../../config/default.config');

/**
 * 判断文件是否存在
 * @param {*} path
 */
function checkFileExists(path) {
  fs.stat(path, (err, stats) => {
    if (err) {
      console.log('文件不存在');
    } else {
      console.log('文件存在,执行删除文件操作');
      // 上传成功后删除文件
      fs.unlink(path, err => {
        if (err) {
          console.log('Error deleting file:', err);
        }
      });
    }
  });
}

/**
 * 上传文件到minio
 * @param {*} fileName 文件名称
 * @param {*} filePath 文件路径
 * @returns
 */
async function uploadFileMinio(fileName, filePath) {
  console.log('上传文件到minio', fileName, filePath);
  //基本配置
  const minioClient = new Minio.Client(MINIOCONFIG);
  let isExist = await minioClient.bucketExists(MINIOCONFIG.bucketName);
  let err = '';
  if (!isExist) {
    //创建桶后，需要在管理界面修改public访问权限，默认是private
    err = await minioClient.makeBucket(MINIOCONFIG.bucketName, 'cn-north-1');
    return {
      code: 1,
      success: false,
      msg: err,
    };
  }

  if (!err) {
    //上传文件
    const data = await minioClient.fPutObject(MINIOCONFIG.bucketName, fileName, filePath);
    console.log('返回给前端的文件路径>>>', data, `${MINIOCONFIG.endPoint}:${MINIOCONFIG.port}/${MINIOCONFIG.bucketName}/${fileName}`);

    // // 获取minio 存储文件路径
    // const url = await minioClient.presignedGetObject(MINIOCONFIG.bucketName, fileName);
    // console.log('返回给前端的文件路径 url>>>', url);

    return {
      code: 0,
      success: true,
      msg: '上传成功',
      data: `http://${MINIOCONFIG.endPoint}:${MINIOCONFIG.port}/${MINIOCONFIG.bucketName}/${fileName}`,
    };
  }
}

/**
 *  上传文件七牛云
 * @param {*} fileName  文件名称
 * @param {*} filePath  文件路径
 * @returns
 */
async function uploadFileQiniu(fileName, filePath) {
  console.log('七牛云上传', { fileName, filePath });
  const putPolicy = new qiniu.rs.PutPolicy({
    scope: QINIUCONFIG.scope, // 存储空间的名字
    returnBody: '{"key":"$(key)","hash":"$(etag)","fsize":$(fsize),"mimeType":"$(mimeType)"}', // 自定义返回体
  });
  const uploadToken = putPolicy.uploadToken(new qiniu.auth.digest.Mac(QINIUCONFIG.accessKey, QINIUCONFIG.secretKey));
  // 实例化formUploader
  const putExtra = new qiniu.form_up.PutExtra();
  // 实例化formUploader
  const formUploader = new qiniu.form_up.FormUploader({
    zone: qiniu.zone.Zone_z1, // 根据你的七牛云存储区域选择对应的zone
  });

  try {
    const { data, resp } = await formUploader.putFile(uploadToken, fileName, filePath, putExtra);
    console.log({ data, resp });
    if (resp.statusCode == 200) {
      const fileKey = data.key;
      const fileUrl = `http://${QINIUCONFIG.domain}/${fileKey}`;
      return {
        code: 0,
        msg: '上传成功',
        data: fileUrl,
        success: true,
      };
    } else {
      return {
        code: 1,
        msg: '上传失败' + resp.statusMessage,
        data: null,
        success: false,
      };
    }
  } catch (error) {
    return {
      code: 1,
      msg: error,
      success: false,
    };
  }
}

const UploadController = {
  upload: async (req, res) => {
    console.log(req, res, '====');
    res.send({
      code: 0,
      msg: '上传成功',
      data: 'uploads/' + req.file.filename,
      success: true,
    });
  },
  uploadQiniu: async (req, res) => {
    const file = req.file;
    // 上传文件
    const data = await uploadFileQiniu(file.filename, file.path);
    res.send({
      code: 1,
      ...data,
    });
    // 上传成功后删除文件
    checkFileExists(file.path);
  },
  uploadMinio: async (req, res) => {
    const file = req.file;
    // 上传文件
    console.log('file', file);
    const fileDate = new Date();
    const dateFolder = `${fileDate.getUTCFullYear()}/${String(fileDate.getUTCMonth() + 1).padStart(2, '0')}/${String(fileDate.getUTCDate()).padStart(2, '0')}`;
    const fileName = `${dateFolder}/${file.filename}`;
    try {
      const data = await uploadFileMinio(fileName, file.path);
      res.send({
        code: 1,
        ...data,
      });
      // 上传成功后删除文件
      checkFileExists(file.path);
    } catch (error) {
      res.send({
        code: 1,
        msg: error,
        success: false,
      });
    }
  },
};

module.exports = UploadController;
